package com.sakhalin.news.viewmodels

import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import com.sakhalin.news.BuildConfig
import com.sakhalin.news.models.news.NewsItemDetails
import com.sakhalin.news.network.DataLoadingState
import com.sakhalin.news.repositories.NewsDetailsRepository
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch

class NewsDetailsViewModel(val id: String, val darkMode: Boolean = false) : BaseViewModel() {

    private val newsDetailsRepository = NewsDetailsRepository()
    private val _newsDetails = MutableStateFlow(NewsItemDetails())
    val newsDetails: StateFlow<NewsItemDetails> get() = _newsDetails

    class Factory(private val id: String, private val darkMode: Boolean = false) : ViewModelProvider.Factory {
        override fun <T : ViewModel> create(modelClass: Class<T>): T {
            return NewsDetailsViewModel(id, darkMode) as T
        }
    }

    init {
        getNews(id)
    }

    fun getNews(id: String){
        viewModelScope.launch {

            try{
                _loadingState.value = DataLoadingState.Loading()
                val response = newsDetailsRepository.getNewsDetails(id, darkMode)

                if (response.isError) {
                    _loadingState.value = DataLoadingState.ErrorLoading(response.errorText)
                }

                val content = checkNotNull(response.content)
                _newsDetails.value = content

                _loadingState.value = DataLoadingState.LoadingSuccess()

            } catch (e: Exception) {
                e.printStackTrace()

                _loadingState.value = DataLoadingState.ErrorLoading(
                    if (BuildConfig.DEBUG) e.message ?: "Неизвестная ошибка"
                    else NO_DATA_ERROR_TEXT
                )
            }
        }
    }
}